const express = require("express");
const bodyParser = require("body-parser");
const app = express();

app.use(express.json());

app.use(express.urlencoded());

app.use(bodyParser.urlencoded({extends: true}))


const models = require("../db/models");

// 查询任务列表
app.get('/list/:status/:page',async (req, res, next) => {
  try {
    let {page,status} = req.params;
    let limit = 10;
    let offset = (page - 1) * limit;
    let where = {};
    if (status !== -1) {
      where.status = status;
    }
    let list =  await models.Todo.findAndCountAll({
      where,
      offset,
      limit
    });
    res.json({
      list,
      message: "列表查询成功"
    });
  }catch (e) {

  }
});
// 创建一个todo
app.post('/create', async (req, res, next) => {
  try {
    let {name,deadline,content,status} = req.body;
    // 持久化到数据库
    let todo = await models.Todo.create({
      name,
      deadline,
      content,
      status
    })
    res.json({
      todo,
      message: "创建任务成功"
    })
  }catch (e) {
    // 传递下去会被全局的异常捕捉到
    next(e);

  }
});
// 修改一个todo
app.post('/update', async (req, res, next) => {
  try {
    let {name, deadline, content, id,status} = req.body;
    let todo = await models.Todo.findOne({
      where:{
        id
      }
    });
    if (todo) {
      todo = await todo.update({
        name,
        deadline,
        content,
        status
      });
    }
    res.json({
      todo,
      message: "修改成功...",
      code: 10000
    });
  }catch (e) {
    next(e);
  }
});
// 修改一个todo，删除
app.post('/update_status', async (req, res, next) => {
  try {
    let {id,status} = req.body;
    let todo = await models.Todo.findOne({
      where:{
        id
      }
    });
    if (todo && status!==todo.status) {
      todo = await todo.update({
        status
      });
    }
    res.json({
      todo,
      message: "状态修改成功...",
      code: 10000
    });
  }catch (e) {
    next(e);

  }

});
app.use((err, req, res, next) => {
  if (err) {
    res.status(500).json({
      message: err.message
    })
  }

});


app.listen(3000, () => {
  console.log("服务启动成功，端口3000...");
});





